import {
  parseTransferNote
} from '@33cn/chain33-transaction-parser'
import AdrList from '../utils/adrTag'
import store from '../store/index'
import i18n from '../config/i18n'

/**
 * 格式化时间
 *
 * @param {date} date
 * @param {string} format
 * @returns
 */
export function formatTime(date, format = 'yyyy-MM-dd hh:mm:ss') {
  if (!date) return ''
  if (typeof date === 'number') {
    if (Math.floor(date / 1e9) > 0 && Math.floor(date / 1e9) < 10) {
      date = date * 1000
    }
    date = new Date(date)
  } else if (typeof date === 'string') {
    // timestamp in secounds
    if (/^\d{10}$/.test(date)) {
      date = new Date(date * 1000)
    } else {
      // ios 中使用 new Date( yyyy-MM-dd hh:mm:ss:SS ) 时间格式字符串不能精确到 小时以后
      var dateArr = date.split(/[- :]/)
      var now = new Date()
      date = new Date(dateArr[0] || now.getFullYear(), dateArr[1] && parseInt(dateArr[1]) ? parseInt(dateArr[1]) - 1 : (now.getMonth() - 1), dateArr[2] || 1, dateArr[3] || 0, dateArr[4] || 0, dateArr[5] || 0)
    }
  } else {
    /* eslint-disable-next-line */
    console.error('wrong format', date)
    return ''
  }

  if (format === 'timestamp') return +date

  var map = {
    'M': date.getMonth() + 1, // 月份
    'd': date.getDate(), // 日
    'h': date.getHours(), // 小时
    'm': date.getMinutes(), // 分
    's': date.getSeconds(), // 秒
    'q': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds(), // 毫秒
    'W': '星期' + ['日', '一', '二', '三', '四', '五', '六'][date.getDay()] // 星期
  }
  format = format.replace(/([yMdhmsqSW])+/g, function (all, t) {
    var v = map[t]
    if (v !== undefined) {
      if (all.length > 1) {
        v = '0' + v
        v = v.substr(v.length - 2)
      }
      return v
    } else if (t === 'y') {
      return (date.getFullYear() + '').substr(4 - all.length)
    }
    return all
  })
  return format
}

// 解码转账交易中的note字段
export let decodeTransferNote = (tx) => {
  let payload = ''
  if (!tx.payload) return tx.rawPayload
  else {
    payload = tx.payload
  }
  const keys = ['transfer', 'withdraw', 'transferToExec']
  const key = keys.find(item => payload[item])
  if (key && payload[key].note) {
    payload[key].note = parseTransferNote(payload[key].note)
  }
  return payload
}

// countdown

// 2270000高度分叉收益区分
export let branchIncome = (num, token) => {
  let base = token || ''
  let branchNum = store.state.apiSetting.provider === 'https://testnode.bityuan.com:8801' ? 1692673 : 2269999
  return Number(num) > branchNum ? `8 ${base}（矿工5+发展基金3）` : `30${base}（矿工18+发展基金12）`
}

/*
 * 截断hash
 */
export let filterHash = (str, num) => {
  let length = num || 12
  return String(str).substr(0, length) + '...' + String(str).substr(-4);
}

// 手续费过滤
export let filterFee = (str) => {
  let token = process.env.VUE_APP_BASECOIN
  if (token === undefined || token === 'BTY') {
    return `${str/100000000} BTY`
  } else {
    return `${process.env.VUE_APP_FEE_TOTAL} ${token}`
  }
}

// 过滤交易组
export let tradeGroup = (trade) => {
  if (trade.tx && trade.tx.groupCount > 1) return i18n.t('txDetail.groupTx')
  else return i18n.t('txDetail.normalTx')
}

/**
 * 获取交易中的价值
 * 强制非科学计数法
 * @param {object} tradeInfo
 */
export let TradeValue = (tradeInfo) => {
  if (!tradeInfo.amount && !tradeInfo.assets) return `0 ${process.env.VUE_APP_BASECOIN}`
  // 燃烧或增发交易
  if (tradeInfo.actionName === 'tokenBurn' || tradeInfo.actionName === 'tokenMint') return `0 ${process.env.VUE_APP_BASECOIN}`
  var res = `${tradeInfo.amount / 100000000} ${process.env.VUE_APP_BASECOIN}`
  if (tradeInfo.assets && tradeInfo.assets.length !== 0 && tradeInfo.assets[0].symbol) {
    var amount = (tradeInfo.assets[0].amount || 0) / 100000000
    var cointoken = tradeInfo.assets[0].symbol
    // var m = amount.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/)
    // amount = amount.toFixed(Math.max(0, (m[1] || '').length - m[2]))
    // /^user\.p\.\w+\.coins$/.test(tradeInfo.tx.execer)
    if (cointoken === 'bty' || cointoken === 'BTY' && /^user\.p\.\w+\.coins$/.test(tradeInfo.assets[0].exec))
      res = `${amount} ${process.env.VUE_APP_BASECOIN}`
    else res = `${amount} ${cointoken}`
  }
  if (tradeInfo.tx && /^user\.p\.\w+\.coins$/.test(tradeInfo.tx.execer)) {
    let symbol = tradeInfo.tx.execer
    let sLen = symbol.length - 13
    symbol = symbol.substr(7, sLen)
    res = res + ` (${symbol})`
  }
  return res
};

/**
 * 获取交易中的token
 * @param {object} tradeInfo  
 */
export let getTradeSymbol = (tradeInfo) => {
  let res = process.env.VUE_APP_BASECOIN
  if (tradeInfo.assets && tradeInfo.assets.length !== 0 && tradeInfo.assets[0].symbol) {
    if (tradeInfo.assets[0].symbol !== 'BTY' && tradeInfo.assets[0].symbol !== 'bty') {
      let cointoken = tradeInfo.assets[0].symbol
      res = `${cointoken}`
    }
  }
  return res
};

// 倒数计时器
export let caculateTime = (time) => {
  let Dt = new Date();
  let local = Dt.getTime();
  let dValue = parseInt(local / 1000 - time);
  let h = parseInt(dValue / 3600);
  dValue -= h * 3600;
  let m = parseInt(dValue / 60);
  dValue -= m * 60;
  let s = parseInt(dValue);
  if (parseInt(local / 1000 - time) >= 86400)
    return formatTime(time);
  else if (parseInt(local / 1000 - time) >= 3600)
    return `${h}${i18n.t('components.hour')}${m}${i18n.t('components.min')}${s}${i18n.t('components.secs')}`;
  else if (parseInt(local / 1000 - time) >= 60)
    return `${m}${i18n.t('components.min')}${s}${i18n.t('components.secs')}`;
  else return `${s}${i18n.t('components.secs')}`;
}

// 数字位数过滤
export let filterNum = (num) => {
  if (!num || num === null || num === '') return
  let n = String(num).split('.')
  let b = parseInt(n[0]).toString();
  let len = b.length;
  let result = ''
  if (len <= 3) {
    result = b;
  } else {
    let r = len % 3;
    result = r > 0 ? b.slice(0, r) + "," + b.slice(r, len).match(/\d{3}/g).join(",") : b.slice(r, len).match(/\d{3}/g).join(",");
  }
  if (n[1]) {
    return result + `.${n[1]}`
  } else {
    return result
  }
}

// 数位转换
export let nFormatter = (num, digits = 2) => {
  const si = [{
      value: 1,
      symbol: ""
    },
    {
      value: 1E3,
      symbol: "K"
    },
    {
      value: 1E6,
      symbol: "M"
    },
    {
      value: 1E9,
      symbol: "G"
    },
    {
      value: 1E12,
      symbol: "T"
    },
    {
      value: 1E15,
      symbol: "P"
    },
    {
      value: 1E18,
      symbol: "E"
    }
  ];
  const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
  let i;
  for (i = si.length - 1; i > 0; i--) {
    if (num >= si[i].value) {
      break;
    }
  }
  return (num / si[i].value).toFixed(digits).replace(rx, "$1") + si[i].symbol;
}

export let scienceNum = (num) => {
  if ((String(num).indexOf('E') != -1) || (String(num).indexOf('e') != -1)) {
    return Number(num.toFixed(9).replace(/\.0+$/, "").replace(/(\.\d+[1-9])0+$/, "$1")).toFixed(8)
  } else return num
}

export let filterAdrTag = (adr) => {
  let result = null
  AdrList.adrList.forEach(item => {
    if (item.adr === adr) result = item.tag
  })
  AdrList.poolist.forEach(item => {
    if (item.adr === adr) result = item.tag
  })
  return result
}

export default {
  formatTime,
  decodeTransferNote,
  branchIncome,
  filterHash,
  filterFee,
  TradeValue,
  tradeGroup,
  getTradeSymbol,
  caculateTime,
  filterNum,
  nFormatter,
  scienceNum,
  filterAdrTag
}